package com.sywb.chuangyebao.contract;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;

import com.aliyun.vodplayer.media.IAliyunVodPlayer;
import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.library.player.AliPlayerView;
import com.sywb.chuangyebao.library.player.IVideoController;
import com.sywb.chuangyebao.library.player.listener.OnPlayerListener;
import com.sywb.chuangyebao.utils.ScreenSwitchUtils;
import com.sywb.chuangyebao.utils.WindowUtil;

import org.bining.footstone.adapter.BaseRecyclerHolder;
import org.bining.footstone.log.Logger;
import org.bining.footstone.rxjava.rxbus.RxBus;

public interface BasePlayerContract {

    interface View extends BaseRefreshContract.View {

        boolean getVisibleToTab();

        boolean getVisibleToUser();
    }

    abstract class Presenter<T extends View> extends BaseRefreshContract.Presenter<T> {

        protected AliPlayerView aliPlayerView;
        protected ScreenSwitchUtils instance;

        //是否处于滚动状态
        private boolean mScrollState = false;

        // item 相关位置信息
        private int lastItemPosition = 0;// 可见的第一个Item位置
        private int firstItemPosition = 0;// 可见的最后一个Item位置
        private int visibleItemCount = 0;// 可见的Item个数

        private int playerPosition = -1;// 正在播放item的位置
        private int lastPlayerPosition = -1;// 上次播放item的位置
        private long currentPosition = 0;// 播放进度
        private boolean isFullScreen;//是否处于全屏状态

        @Override
        public void onStart() {
            super.onStart();
            commonRecycler.addOnScrollListener(new MyScrollListener());
            instance = ScreenSwitchUtils.init(mContext.getApplicationContext());
            initPlayerView();
        }

        public void initPlayerView() {
            if (aliPlayerView != null) {
                aliPlayerView.destroy();
            }
            aliPlayerView = new AliPlayerView(mContext);
            aliPlayerView.init(IVideoController.MODE_VIDEO);
            aliPlayerView.setOnPlayerListener(new OnPlayerListener() {

                @Override
                public void onInit() {
                }

                @Override
                public void onPrepared() {
                }

                @Override
                public void onStarted() {
                    if (mView != null && mView.getVisibleToUser() && mView.getVisibleToTab()) {
                        instance.start(mActivity);
                    } else {
                        autoPause();
                    }
                }

                @Override
                public void onPaused() {
                    instance.stop();
                    if (playerPosition >= 0) {
                        itemRemovePlayerView();
                        saveItemPlayerCurrentPosition(playerPosition, aliPlayerView.getAliyunVodPlayer().getCurrentPosition());
                        playerPosition = -1;
                        lastPlayerPosition = -1;
                    }
                }

                @Override
                public void onCompletion() {
                    instance.stop();
                    if (playerPosition >= 0) {
                        itemRemovePlayerView();
                        saveItemPlayerCurrentPosition(playerPosition, 0);
                        playerPosition = -1;
                        lastPlayerPosition = -1;
                        aliPlayerView.setCanReplay(true);
                    }
                }

                @Override
                public void onError(int causeCode, int sceneCode, String message) {
                    instance.stop();
                }

                @Override
                public void onShare(int platformType) {
                }

                @Override
                public void onClickScreenDirection() {
                    instance.toggleScreen();
                }

                @Override
                public void showToolsView() {
                }

                @Override
                public void hideToolsView() {
                }

                @Override
                public void updateProgress(int curPosition, int bufferPosition, int duration) {
                }
            });
        }

        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            int videoId = data.getIntExtra("p0", 0);
            int postion = data.getIntExtra("p1", 0);
            currentPosition = data.getLongExtra("p2", 0L);
            Logger.e("onActivityResult videoId：" + videoId + " postion：" + postion + " currentPosition：" + currentPosition);

            if (playerPosition == postion) {
                aliPlayerView.autoResume();
                if (currentPosition > 0) {
                    aliPlayerView.seekTo((int) currentPosition);
                    currentPosition = 0L;
                }
            }
        }

        public void onConfigurationChanged(Configuration newConfig) {
            if (mView == null || !mView.getVisibleToTab() || !mView.getVisibleToUser()) {
                return;
            }
            RxBus.get().post(Constants.ISFULLSCREEN, String.valueOf(newConfig.orientation));
            boolean orientation = newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE;//屏幕方向是否为横屏
            Logger.e("屏幕方向改变！！！是否为横屏：" + orientation);
            aliPlayerView.onConfigurationChanged(newConfig);
            if (orientation) {// 横屏
                if (mActivity == null) return;
                Activity activity = WindowUtil.scanForActivity(mActivity);
                if (activity == null) return;
                if (isFullScreen) return;
                isFullScreen = true;
                WindowUtil.hideSystemBar(mActivity);
                if (itemRemovePlayerView()) {
                    ViewGroup contentView = activity.findViewById(android.R.id.content);
                    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                    contentView.addView(aliPlayerView, params);
                } else {
                    mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
            } else {// 竖屏
                if (mActivity == null) return;
                Activity activity = WindowUtil.scanForActivity(mActivity);
                if (activity == null) return;
                if (!isFullScreen) return;
                isFullScreen = false;
                WindowUtil.showSystemBar(mActivity);
                ViewGroup contentView = activity.findViewById(android.R.id.content);
                contentView.removeView(aliPlayerView);
                itemAddPlayerView();
            }
        }

        public boolean itemAddPlayerView() {
            Logger.e("itemAddPlayerView");
            BaseRecyclerHolder childViewHolder = (BaseRecyclerHolder) commonRecycler.findViewHolderForAdapterPosition(playerPosition);
            if (childViewHolder != null) {
                FrameLayout llContainer = childViewHolder.getViewHolderHelper().getView(R.id.ll_container);
                if (llContainer.getChildCount() > 0) {
                    llContainer.removeAllViews();
                }
                FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                llContainer.addView(aliPlayerView, params);
                return true;
            } else {
                Logger.e("itemAddPlayerView 未获取到BaseRecyclerHolder，playerPosition = " + playerPosition);
                autoPause();
            }
            return false;
        }

        public boolean itemRemovePlayerView() {
            Logger.e("itemRemovePlayerView");
            BaseRecyclerHolder childViewHolder = (BaseRecyclerHolder) commonRecycler.findViewHolderForAdapterPosition(playerPosition);
            if (childViewHolder != null) {
                FrameLayout llContainer = childViewHolder.getViewHolderHelper().getView(R.id.ll_container);
                llContainer.removeAllViews();
                return true;
            } else {
                Logger.e("itemRemovePlayerView 未获取到BaseRecyclerHolder，playerPosition = " + playerPosition);
            }
            return false;
        }

        /**
         * 列表的滚动监听
         */
        private class MyScrollListener extends RecyclerView.OnScrollListener {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                Logger.e("onScrollStateChanged");
                super.onScrollStateChanged(recyclerView, newState);
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_DRAGGING:// 用户用手指滚动
                        mScrollState = true;
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING:// 自动滚动
                        mScrollState = true;
                        break;
                    case RecyclerView.SCROLL_STATE_IDLE:// 停止滑动
                        mScrollState = false;
                        //滑动停止和松开手指时，调用此方法 进行播放
//                        if (playerPosition >= 0 && playerPosition >= firstItemPosition && playerPosition <= lastItemPosition) {
//                            if (getVisibilityPercents(recyclerView, playerPosition - firstItemPosition) >= 95) {
//                                itemAddPlayerView();
//                                aliPlayerView.autoResume();
//                                lastPlayerPosition = -1;
//                            }
//                        } else if (lastPlayerPosition >= 0 && lastPlayerPosition >= firstItemPosition && lastPlayerPosition <= lastItemPosition) {
//                            if (getVisibilityPercents(recyclerView, lastPlayerPosition - firstItemPosition) >= 95) {
//                                playerPosition = lastPlayerPosition;
//                                itemAddPlayerView();
//                                aliPlayerView.autoResume();
//                                lastPlayerPosition = -1;
//                            }
//                        }
                        break;
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                Logger.e("onScrolled");
                RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager linearManager = (LinearLayoutManager) layoutManager;
                    // 获取第一个可见view的位置
                    firstItemPosition = linearManager.findFirstVisibleItemPosition();
                    //  获取最后一个可见view的位置
                    lastItemPosition = linearManager.findLastVisibleItemPosition();
                    // 获取可见view的总数
                    visibleItemCount = linearManager.getChildCount();

                    Logger.e("onScrolled firstItemPosition：" + firstItemPosition + " lastItemPosition:" + lastItemPosition + " visibleItemCount" + visibleItemCount);

                    if (mScrollState) {// 滚动
                        if (playerPosition >= 0) {
                            if (playerPosition < firstItemPosition || playerPosition > lastItemPosition || getVisibilityPercents(recyclerView, playerPosition - firstItemPosition) < 45) {
                                autoPause();
                            }
                        } else if (aliPlayerView.getPlayerState() == IAliyunVodPlayer.PlayerState.Started) {
                            playerPosition = -1;
                            lastPlayerPosition = -1;
                            aliPlayerView.stop();
                            instance.stop();
                        }
                    }
                }
            }
        }

        /**
         * 获取指定位置的Item的可见百分比
         */
        private int getVisibilityPercents(RecyclerView recyclerView, int position) {
            int visibilityPercents = 0;
            if (recyclerView != null) {
                android.view.View childAt = recyclerView.getChildAt(position).findViewById(R.id.ll_container);
                if (childAt == null) {
                    return visibilityPercents;
                }
                Rect mCurrentViewRect = new Rect();
                childAt.getLocalVisibleRect(mCurrentViewRect);
                int height = childAt.getHeight();
                int top = mCurrentViewRect.top;
                int bottom = mCurrentViewRect.bottom;
                if (top >= 0) {
                    visibilityPercents = (bottom - top) * 100 / height;
                } else if (bottom < 0) {
                    visibilityPercents = 0;
                }
            }
            return visibilityPercents;
        }

        public void saveItemPlayerCurrentPosition(int postion, long currentPosition) {
            Logger.e("saveItemPlayerCurrentPosition postion:" + postion + " currentPosition:" + currentPosition);
        }

        /**
         * 添加播放器并开始播放视频，并获取之前的播放进度
         */
        public boolean startPlayer(int position, String playerUrl, String previewUrl, long currentPosition) {
            Logger.e("startPlayer " + position + " playerPosition:" + playerPosition + " lastPlayerPosition:" + lastPlayerPosition);
            if (mView != null && mView.getVisibleToUser() && mView.getVisibleToTab() && position >= 0) {
                if (lastPlayerPosition >= 0) {
                    if (lastPlayerPosition == position) {
                        playerPosition = lastPlayerPosition;
                        autoResume();
                        return true;
                    } else {
                        playerPosition = -1;
                        lastPlayerPosition = -1;
                        aliPlayerView.destroy();
                    }
                } else if (playerPosition >= 0) {
                    if (playerPosition == position) {
                        autoResume();
                        return true;
                    } else {
                        itemRemovePlayerView();
                        saveItemPlayerCurrentPosition(playerPosition, aliPlayerView.getAliyunVodPlayer().getCurrentPosition());
                        playerPosition = -1;
                        lastPlayerPosition = -1;
                        aliPlayerView.destroy();
                    }
                }
                playerPosition = position;
                lastPlayerPosition = -1;
                aliPlayerView.start(mActivity, playerUrl, previewUrl, "00:00");
                if (currentPosition > 0) {
                    aliPlayerView.seekTo((int) currentPosition);
                }
                itemAddPlayerView();
            }
            return false;
        }

        /**
         * 停止播放视频
         */
        public void stopPlayer(int position) {
            Logger.e("stopPlayer " + position);
            if (position >= 0 && position == playerPosition) {
                itemRemovePlayerView();
                saveItemPlayerCurrentPosition(playerPosition, aliPlayerView.getAliyunVodPlayer().getCurrentPosition());
                lastPlayerPosition = playerPosition;
                playerPosition = -1;
                aliPlayerView.pause();

                instance.stop();
            }
        }

        public void autoResume() {
            Logger.e("autoResume " + playerPosition);
            if (mView != null && mView.getVisibleToUser() && mView.getVisibleToTab() && playerPosition >= 0) {
                lastPlayerPosition = -1;
                aliPlayerView.autoResume();
                itemAddPlayerView();
            }
        }

        public void autoPause() {
            Logger.e("autoPause " + playerPosition);
            if (playerPosition >= 0) {
                itemRemovePlayerView();
                saveItemPlayerCurrentPosition(playerPosition, aliPlayerView.getAliyunVodPlayer().getCurrentPosition());
                lastPlayerPosition = playerPosition;
                playerPosition = -1;
                aliPlayerView.autoPause();

                instance.stop();
            }
        }

        public void onStartRefresh() {
            autoPause();
            lastPlayerPosition = -1;
        }

        public void setUserVisibleHint() {
            if (commonRecycler != null && commonRecycler.getChildCount() > 0) {
                if (mView != null && mView.getVisibleToUser() && mView.getVisibleToTab()) {
                    autoResume();
                } else {
                    autoPause();
                }
            }
        }

        @Override
        public void onDestroy() {
            if (aliPlayerView != null) {
                aliPlayerView.destroy();
            }
            super.onDestroy();
        }
    }
}
